package com.mysteel.order.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysteel.common.exception.BizCodeEnum;
import com.mysteel.common.to.SkuHasStockTo;
import com.mysteel.common.to.mq.OrderTo;
import com.mysteel.common.to.mq.SecKillOrderTo;
import com.mysteel.common.utils.PageUtils;
import com.mysteel.common.utils.Query;
import com.mysteel.common.vo.MemberResponseVo;
import com.mysteel.order.config.AlipayTemplate;
import com.mysteel.order.constant.OrderConstant;
import com.mysteel.order.dao.OrderDao;
import com.mysteel.order.entity.OrderEntity;
import com.mysteel.order.entity.OrderItemEntity;
import com.mysteel.order.entity.PaymentInfoEntity;
import com.mysteel.order.enume.OrderStatusEnum;
import com.mysteel.order.exception.CommonException;
import com.mysteel.order.feign.CartFeignService;
import com.mysteel.order.feign.MemberFeignService;
import com.mysteel.order.feign.ProductFeignService;
import com.mysteel.order.feign.WmsFeignService;
import com.mysteel.order.interceptor.LoginUserInterceptor;
import com.mysteel.order.service.OrderItemService;
import com.mysteel.order.service.OrderService;
import com.mysteel.order.service.PaymentInfoService;
import com.mysteel.order.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private WmsFeignService wmsFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.threadLocal.get();
        // 从主线程中获取请求数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            // 将主线程的请求数据设置到子线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询用户所有收货地址
            List<MemberAddressVo> address = memberFeignService.getAddressByMemberId(memberResponseVo.getId());
            confirmVo.setAddress(address);
        }, threadPoolExecutor);

        CompletableFuture<Void> orderItemFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 查询远程购物车的购物项
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(currentUserCartItems);
        }, threadPoolExecutor).thenRunAsync(() -> {
            // 批量查询商品库存信息
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            List<SkuHasStockTo> skuHasStock = wmsFeignService.getSkuHasStock(collect);
            if (CollectionUtils.isEmpty(skuHasStock)) {
                confirmVo.setStocks(new HashMap<>(0));
            }
            Map<Long, Boolean> stocks = skuHasStock.stream()
                    .collect(Collectors.toMap(SkuHasStockTo::getSkuId,
                            value -> skuHasStock.stream()
                                    .filter(item -> value.getSkuId().equals(item.getSkuId()))
                                    .anyMatch(SkuHasStockTo::isHasStock)
                            , (k, v) -> v));
            confirmVo.setStocks(stocks);
        }, threadPoolExecutor);

        // 查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        confirmVo.setIntegration(integration == null ? 0 : integration);

        // todo 防重复提交令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(), token, 30, TimeUnit.MINUTES);

        try {
            CompletableFuture.allOf(addressFuture, orderItemFuture).get();
        } catch (Exception e) {
            log.error("调用远程接口异常：{}", e);
        }

        return confirmVo;
    }

    /**
     * Transactional:本地事务，只能控制自己的回滚，无法控制远程事务事务回滚
     * 存在问题：
     * 1、远程事务假失败：远程调用成功，但返回的时候由于网络等原因，调用结果为失败
     *      导致问题：远程服务事务未回滚，调用方事务回滚，数据不一致
     * 2、远程服务执行成功，其它方法执行失败抛异常
     *      导致问题：远程服务事务未回滚，调用方事务回滚，数据不一致
     * 本地事务失效问题：同一个对象内事务方法互调默认失效
     *      原因：事务是使用代理对象来控制的，而上述调用方式绕过了代理对象
     *      解决方案：使用代理对象调用事务方法
     *          1、引入spring-boot-starter-aop，引入了aspectJ
     *          2、@EnableAspectJAutoProxy(exposeProxy = true)：开启aspectJ动态代理，没有接口也能动态代理（默认使用JDK动态代理，依赖接口代理）
     *              exposeProxy = true：对外暴露代理对象
     *          3、用代理对象（获取代理对象，AopContext.currentProxy()）调用同类方法
     *
     * 分布式事务：
     *  CAP定理：
     *      一致性：
     *      可用性：
     *      分区容错性：
     *
     *  BASE原则：
     *
     *  Seata控制分布式事务：
     *  1、每个微服务数据库都创建undo_log表
     *  2、安装事务协调器：https://github.com/seata/seata/releases
     *
     *
     * 下单高并发场景不适合使用AT机制
     */
//    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) throws CommonException {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.threadLocal.get();
        // 验证令牌信息[令牌的对比和删除必须保持原子性]
        String orderToken = orderSubmitVo.getOrderToken();
        String redisTokenKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId();
        // 脚本返回结果：0，失败；1：成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(redisTokenKey), orderToken);
        if (result == null || result == 0) {
            throw new CommonException(BizCodeEnum.ORDER_TOKEN_INVALID_EXCEPTION.getCode(),BizCodeEnum.ORDER_TOKEN_INVALID_EXCEPTION.getMsg());
        }
        // 组装订单数据
        OrderCreateTo order = createOrder(orderSubmitVo);
        if (order == null){
            throw new CommonException(BizCodeEnum.ORDER_ITEM_INFO_EXCEPTION.getCode(),BizCodeEnum.ORDER_ITEM_INFO_EXCEPTION.getMsg());
        }
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = orderSubmitVo.getPayPrice();
        if (Math.abs(payAmount.subtract(payPrice).doubleValue()) > 0.01){
            throw new CommonException(BizCodeEnum.ORDER_PRICE_CHECK_EXCEPTION.getCode(),BizCodeEnum.ORDER_PRICE_CHECK_EXCEPTION.getMsg());
        }
        // 保存订单
        saveOrder(order);
        // 锁定库存，只要有异常，回滚订单数据
        WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
        wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
        List<OrderItemVo> locks = order.getItems().stream().map(orderItemEntity -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setSkuId(orderItemEntity.getSkuId());
            orderItemVo.setCount(orderItemEntity.getSkuQuantity());
            orderItemVo.setTitle(orderItemEntity.getSkuName());
            return orderItemVo;
        }).collect(Collectors.toList());
        wareSkuLockVo.setLocks(locks);
        boolean stockLockResult = wmsFeignService.lockOrderStock(wareSkuLockVo);
        if (!stockLockResult){
            // 库存锁定失败,抛异常，事务回滚
            throw new CommonException(BizCodeEnum.ORDER_STOCK_NOT_ENOUGH.getCode(),BizCodeEnum.ORDER_STOCK_NOT_ENOUGH.getMsg());
        }
        // 订单创建成功，发送消息给交换机
        rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
        responseVo.setCode(1);
        responseVo.setOrder(order.getOrder());
        return responseVo;
    }

    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        // 保存订单数据
        this.baseMapper.insert(orderEntity);
        // 保存订单项数据
        orderItemService.saveBatch(order.getItems());
    }

    /**
     * 组装订单数据
     * @return
     */
    private OrderCreateTo createOrder(OrderSubmitVo orderSubmitVo) throws CommonException {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 组装用户收货信息
        OrderEntity orderEntity = buildOrder(orderSubmitVo);
        // 组装订单项信息
        List<OrderItemEntity> orderItems = buildOrderItems(orderEntity.getOrderSn());
        orderCreateTo.setItems(orderItems);
        // 验价
        OrderEntity resultOrder = computePrice(orderEntity, orderItems);
        orderCreateTo.setOrder(resultOrder);


        return orderCreateTo;
    }

    /**
     * 计算价格信息
     * @param orderEntity
     * @param orderItems
     * @return
     */
    private OrderEntity computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        BigDecimal totalPrice = new BigDecimal(0);
        BigDecimal totalCouponPrice = new BigDecimal(0);
        BigDecimal totalIntegrationPrice = new BigDecimal(0);
        BigDecimal totalPromotionPrice = new BigDecimal(0);
        Integer giftIntegration = 0;
        Integer giftGrowth = 0;
        for (OrderItemEntity orderItem : orderItems) {
            totalPrice = totalPrice.add(orderItem.getRealAmount());
            totalCouponPrice = totalCouponPrice.add(orderItem.getCouponAmount());
            totalIntegrationPrice = totalIntegrationPrice.add(orderItem.getIntegrationAmount());
            totalPromotionPrice = totalPromotionPrice.add(orderItem.getPromotionAmount());
            giftIntegration += orderItem.getGiftIntegration();
            giftGrowth += orderItem.getGiftGrowth();
        }
        orderEntity.setTotalAmount(totalPrice);
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(totalCouponPrice);
        orderEntity.setIntegrationAmount(totalIntegrationPrice);
        orderEntity.setPromotionAmount(totalPromotionPrice);
        orderEntity.setGrowth(giftGrowth);
        orderEntity.setIntegration(giftIntegration);
        orderEntity.setDeleteStatus(0);
        return orderEntity;

    }

    /**
     * 构建订单信息
     * @param orderSubmitVo
     * @return
     * @throws CommonException
     */
    private OrderEntity buildOrder(OrderSubmitVo orderSubmitVo) throws CommonException {
        OrderEntity orderEntity = new OrderEntity();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.threadLocal.get();
        // mybatis 工具类按时间生成订单号
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberResponseVo.getId());
        // 获取收货地址信息
        FareVo fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        if (fare == null){
            // 收货地址信息有误
            throw new CommonException(BizCodeEnum.ORDER_FARE_ADDRESS_EXCEPTION.getCode(),BizCodeEnum.ORDER_FARE_ADDRESS_EXCEPTION.getMsg());
        }
        orderEntity.setFreightAmount(fare.getFare());
        orderEntity.setReceiverCity(fare.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fare.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fare.getAddress().getName());
        orderEntity.setReceiverPhone(fare.getAddress().getPhone());
        orderEntity.setReceiverProvince(fare.getAddress().getProvince());
        orderEntity.setReceiverPostCode(fare.getAddress().getPostCode());
        orderEntity.setReceiverRegion(fare.getAddress().getRegion());
        // 设置订单状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    /**
     * 构建所有订单项
     * @return
     * @throws CommonException
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) throws CommonException {
        // 获取所有的订单项
        List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
        if (CollectionUtils.isEmpty(cartItems)){
            throw new CommonException(BizCodeEnum.ORDER_ITEM_INFO_EXCEPTION.getCode(),BizCodeEnum.ORDER_ITEM_INFO_EXCEPTION.getMsg());
        }
        return cartItems.stream().map(item -> {
            OrderItemEntity orderItemEntity = buildSingleOrderItem(item);
            orderItemEntity.setOrderSn(orderSn);
            return orderItemEntity;
        }).collect(Collectors.toList());
    }

    /**
     * 构建单个订单项
     * @param orderItemVo
     * @return
     */
    private OrderItemEntity buildSingleOrderItem(OrderItemVo orderItemVo){
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 商品的spu信息
        SpuInfoVo spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(orderItemVo.getSkuId());
        orderItemEntity.setSpuId(spuInfoBySkuId.getId());
        orderItemEntity.setSpuBrand(spuInfoBySkuId.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoBySkuId.getSpuName());
        orderItemEntity.setCategoryId(spuInfoBySkuId.getCatalogId());
        // 商品的sku信息
        orderItemEntity.setSkuId(orderItemVo.getSkuId());
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuPic(orderItemVo.getImg());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());
        // 积分信息
        orderItemEntity.setGiftGrowth(orderItemVo.getPrice().intValue());
        orderItemEntity.setGiftIntegration(orderItemVo.getPrice().intValue());
        // 价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal(0));
        orderItemEntity.setIntegrationAmount(new BigDecimal(0));
        orderItemEntity.setCouponAmount(new BigDecimal(0));
        BigDecimal originPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        BigDecimal realPrice = originPrice.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getIntegrationAmount()).subtract(orderItemEntity.getPromotionAmount());
        orderItemEntity.setRealAmount(realPrice);

        return orderItemEntity;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) throws CommonException {
        OrderEntity byId = this.getById(orderEntity.getId());
        if (byId != null && OrderStatusEnum.CREATE_NEW.getCode().equals(orderEntity.getStatus())){
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(orderEntity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateEntity);
            // 再次将订单消息发给mq
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(byId,orderTo);
            try{
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e){
                // 消息发送失败，需要重试，在数据库记录消息发送日志，定期扫描数据库重发消息
            }

        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderByOrderSn = this.getOrderByOrderSn(orderSn);

        List<OrderItemEntity> orderItemList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemList.get(0);
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject(orderItemEntity.getSkuAttrsVals());
        payVo.setTotal_amount(orderByOrderSn.getPayAmount().setScale(2,BigDecimal.ROUND_UP).toString());
        payVo.setBody(orderItemEntity.getSkuName());
        return payVo;
    }

    /**
     * 查询当前登录用户的所有订单信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberResponseVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> collect = page.getRecords().stream().peek(orderEntity -> {
            List<OrderItemEntity> orderItemList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderEntity.getOrderSn()));
            orderEntity.setItemList(orderItemList);
        }).collect(Collectors.toList());

        page.setRecords(collect);

        return new PageUtils(page);
    }

    @Override
    public String handleAliPayNotify(PayAsyncVo asyncVo,Map<String, String[]> requestParams) throws AlipayApiException, UnsupportedEncodingException {
        // 保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfoEntity.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfoEntity.setCallbackTime(asyncVo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);

        if ("TRADE_SUCCESS".equals(asyncVo.getTrade_status()) || "TRADE_FINISHED".equals(asyncVo.getTrade_status())){
            // 验签
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<>();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = iter.next();
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type());
            if (signVerified){
                log.info("支付宝验签成功...");
                // 修改订单状态信息
                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setStatus(OrderStatusEnum.RECIEVED.getCode());
                this.baseMapper.update(orderEntity,new UpdateWrapper<OrderEntity>().eq("order_sn",asyncVo.getOut_trade_no()));
                return "success";
            }
            return "failed";
        }

        return null;
    }

    @Override
    public void createSecKillOrder(SecKillOrderTo secKillOrderTo) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(secKillOrderTo.getOrderSn());
        orderEntity.setMemberId(secKillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = secKillOrderTo.getSeckillPrice().multiply(new BigDecimal(secKillOrderTo.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        // 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(secKillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(secKillOrderTo.getNum());
        // todo 获取当前商品的详细信息进行设置
        orderItemService.save(orderItemEntity);

    }
}